package jwtutil

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	_ "github.com/dgrijalva/jwt-go"
	"personal-skill/models"
	"time"
)
const (
	SECRETKEY = "243223ffslsfsldfl412fdsfsdf"
	EXPIRE = 60 * 60 * 2
)

type UserClaims struct {
	models.User
	jwt.StandardClaims
}

// GenJwtToken 传入用户信息获取token
func GenJwtToken(user *models.User) string {
	userClaims := UserClaims{
		User:           *user,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Add(time.Second * EXPIRE).Unix(),
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, userClaims)
	tokenStr, err := token.SignedString([]byte(SECRETKEY))
	if err != nil {
		return ""
	}
	return tokenStr
}

// ParseJwtToken 解析token
func ParseJwtToken(userToken string) *models.User {
	token, err := jwt.ParseWithClaims(userToken, &UserClaims{}, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}
		return []byte(SECRETKEY), nil
	})
	if err != nil {
		return nil
	}
	if userClaims, ok := token.Claims.(*UserClaims); ok && token.Valid {
		user := models.User{
			Id:            userClaims.User.Id,
			Username:      userClaims.Username,
			Password:      userClaims.Password,
			LastLoginTime: userClaims.LastLoginTime,
			CreateTime:    userClaims.CreateTime,
			UpdateTime:    userClaims.UpdateTime,
		}
		return &user
	}
	return nil
}
